#include "LevelManager.h"
#include "../Menu/MenuManager.h"
#include "Object/LevelGhostObj.h"
#include "../Play/PlayManager.h"
#include "../../Data/GameData.h"
#include <cocostudio/cocostudio.h>
#define LEVEL_PER_PAGE 20
#define LEVEL_ROW 4
#define LEVEL_COL 5

using namespace cocostudio;

bool LevelManager::m_isActive = false;
ELevelMode LevelManager::m_ELevelMode = ELevelMode::Easy;
int LevelManager::currID = 0;
cocos2d::Scene* LevelManager::createScene(ELevelMode levelMode)
{
    auto scene  = Scene::create();
    
    auto layer = LevelManager::create();
    layer->m_ELevelMode = levelMode;
    layer->initBackground();
    layer->initalize();
    scene->addChild(layer);
    return scene;
}

// on "init" you need to initialize your instance
bool LevelManager::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    setKeypadEnabled(true);
    
    m_screenSize = Director::getInstance()->getVisibleSize();
    kSpriteHeight = 250;
    kSpriteWidth = 200;
    LevelManager::m_isActive = false;
    
    return true;
}
void LevelManager::initBackground()
{
	Sprite* background = nullptr;
    switch (m_ELevelMode) {
        case Easy:
            background = Sprite::create("bg_easy.png");
            break;
        case Normal:
            background = Sprite::create("bg_normal.png");
            break;
        case Hard:
            background = Sprite::create("bg_hard.png");
            break;
        default:
            break;
    }
    float scaleX = m_screenSize.width/background->getContentSize().width;
    float scaleY = m_screenSize.height/background->getContentSize().height;
    background->setScale(scaleX, scaleY);
    //  cocos2d::Vector<Node*> list = node->getChildren();
    background->setAnchorPoint(Vec2(0.5f,0.5f));
    background->setPosition(Vec2(m_screenSize.width / 2, m_screenSize.height / 2));
    this->addChild(background);
}
void LevelManager::initalize()
{
    initLevelPanel();
    initButton();
    this->scheduleUpdate();
}
void LevelManager::initLevelPanel()
{
    currPage = 1;
	float rateLevelPerPage;
	int maxLevel = 0;
	switch (m_ELevelMode)
	{
	case ELevelMode::Easy:
		rateLevelPerPage = (float)GameData::getInstance()->config.NumOfEasyLevel / (float)LEVEL_PER_PAGE;
		maxLevel = GameData::getInstance()->config.NumOfEasyLevel;
		break;
	case ELevelMode::Normal: 
		rateLevelPerPage = (float)GameData::getInstance()->config.NumOfNormalLevel / (float)LEVEL_PER_PAGE;
		maxLevel = GameData::getInstance()->config.NumOfNormalLevel;
		break;
	case ELevelMode::Hard: 
		rateLevelPerPage = (float)GameData::getInstance()->config.NumOfHardLevel / (float)LEVEL_PER_PAGE;
		maxLevel = GameData::getInstance()->config.NumOfHardLevel;
		break;
	}

	if (rateLevelPerPage == (int)rateLevelPerPage)
		numPage = (int)rateLevelPerPage;
	else
		numPage = (int)rateLevelPerPage + 1;



    float canvasRow = m_screenSize.height/(LEVEL_ROW + 1);
    levelPanel = Node::create();
    levelPanel->setAnchorPoint(Vec2(0, 1.0f));
    
    levelPanel->setPosition(0,canvasRow * 4);
    
    float expectGhostHeight = canvasRow*0.6f;
    float scale = expectGhostHeight/kSpriteHeight;
    kSpriteHeight*= scale;
    kSpriteWidth *= scale;
    
    kPaddingHeight = canvasRow - kSpriteHeight;
    kPaddingWidth = m_screenSize.width/(LEVEL_COL + 1);
    // char s[100];
    float space = (m_screenSize.width - (kSpriteWidth * LEVEL_COL) - (kPaddingWidth * 2)) / (LEVEL_COL - 1);
    
    int currLevel = 1;
	bool limit = false;
    char s[100];
    for(int iPage = 1; iPage <= numPage; iPage++)
    {

        Node* page = Node::create();
        page->setAnchorPoint(Vec2(0, 1.0f));
        page->setPosition(Vec2((iPage - 1) * m_screenSize.width, 0));
        
        for(int i = 0; i < LEVEL_ROW; i++)
        {
            for(int j = 0; j < LEVEL_COL; j++)
            {
                //                sprintf(s,"stage_%d",currLevel);
                //                bool ok = false;
                //                if(UserDefault::getInstance()->getIntegerForKey(s, 0) == 0)
                //                    sprintf(s,"main_select_stage_lock.png");
                //                else
                //                {
                //                    sprintf(s,"main_select_stage_%d.png",currLevel);
                //                    ok = true;
                //                }
                //
                LevelGhostObj* ghost = new LevelGhostObj();
                sprintf(s,"%d",currLevel);
                //     bool ok = false;
                cocos2d::Vec2 position = Vec2(kPaddingWidth + kSpriteWidth / 2 + j * kSpriteWidth + (j * space),
                                              kSpriteHeight / 2 - i * kSpriteHeight - (i * kPaddingHeight));
                switch (m_ELevelMode) {
                    case Easy:
                        ghost->initGhost("ghost_blue.png",s,position,scale);
                        break;
                    case Normal:
                        ghost->initGhost("ghost_red.png",s,position,scale);
                        
                        break;
                    case Hard:
                        ghost->initGhost("ghost_purple.png",s,position,scale);
                        
                        break;
                    default:
                        break;
                }
                //= Sprite::create("ghost_yellow.png");
                
                //                if(ok)
                //                {
                //                    sprintf(s,"%d",currLevel);
                //                    level->setName(s);
                //                }
                //                else
                //                {
                //                    sprintf(s,"%d", -1);
                //                    level->setName(s);
                //
                //                }
                //
                
                
                BaseGhostObj::addToLayer(page, ghost);
                
                currLevel++;

				if (currLevel - 1 == maxLevel)
				{
					limit = true;
					break;
				}
            }
			if (limit)
				break;
        }
        levelPanel->addChild(page);

		if (limit)
			break;
    }
    this->addChild(levelPanel);
}
void LevelManager::initButton()
{
    Button* btnBack = Button::create("arrow_home.png");
    btnBack->setRotation(180);
    
    float rowHeight = m_screenSize.height/(LEVEL_ROW + 1);
    float expectBackHeight = rowHeight*0.7;
    float backScale = expectBackHeight/btnBack->getContentSize().height;
    btnBack->setScale(backScale);
    btnBack->setPosition(Vec2(btnBack->getContentSize().width*backScale/2 + 20 ,expectBackHeight/2 + 20));
    btnBack->addClickEventListener(CC_CALLBACK_0(LevelManager::ReturnMenuScene, this));
    this->addChild(btnBack);
    
    float kButtonPadding = kPaddingWidth*3/2;
    
    
    float space = (m_screenSize.width - (kSpriteWidth * numPage) - (kButtonPadding * 2)) / (numPage - 1);
    for(int i= 0; i < numPage;i++)
    {
        
        Button* btnPage = Button::create("page-marker.png", "page-marker_over.png","page-marker_over.png");
        btnPage->addClickEventListener(CC_CALLBACK_1(LevelManager::gotoPage, this));
        btnPage->setTag(i + 1);
        if(i==0)
        {
            btnPage->setEnabled(false);
            btnPage->loadTextureNormal("page-marker_over.png");
        }
        m_vectorPage.pushBack(btnPage);
        
        float expectButtonPageHeight = rowHeight*0.3f;
        float ButtonPageScale = expectButtonPageHeight/btnPage->getContentSize().height;
        btnPage->setScale(ButtonPageScale);
        btnPage->setPosition(Vec2(kButtonPadding + btnPage->getContentSize().width*ButtonPageScale / 2 + i * btnPage->getContentSize().width*ButtonPageScale + (i * space),btnBack->getPosition().y));
        this->addChild(btnPage);
    }
}
void LevelManager::ReturnMenuScene()
{
    Director::getInstance()->replaceScene(TransitionCrossFade::create(0.5f, MenuManager::createScene()));
}
void LevelManager::gotoPage(cocos2d::Ref *pSender)
{
    if(LevelManager::m_isActive)
        return;
    Button* btnPage = (Button*)pSender;
    for(int i= 0; i< numPage;i++)
    {
        Button* btn = m_vectorPage.at(i);
        if(btn->getTag() != btnPage->getTag())
        {
            btn->setEnabled(true);
            btn->loadTextureNormal("page-marker.png");
        }
        else
        {
            btn->setEnabled(false);
            
            btn->loadTextureNormal("page-marker_over.png");
            float distanceMove = -m_screenSize.width* (btn->getTag() - currPage);
            currPage = btn->getTag();
            levelPanel->runAction(MoveBy::create(0.5f, Vec2(distanceMove,0)));
        }
    }
    
}


void LevelManager::checkClickButton()
{
    
}
void LevelManager::btnCloseClick(cocos2d::Ref *pSender)
{
    pnlSettings->setVisible(false);
}
void LevelManager::btnSettingClick(cocos2d::Ref *pSender)
{
    Point p = pnlSettings->getPosition();
    pnlSettings->setOpacity(0);
    pnlSettings->setVisible(true);
    //pnlSettings->setScale(0.2f);
    pnlSettings->runAction(FadeIn::create(0.2f));
    pnlSettings->setPosition(pnlSettings->getPosition().x - 100,pnlSettings->getPosition().y);
    pnlSettings->runAction(MoveTo::create(0.2f, p));
    //pnlSettings->runAction(ScaleTo::create(0.2f,1.0f));
}
void LevelManager::GoToGamePlayScene()
{
    Director::getInstance()->replaceScene(TransitionFade::create(0.5f,PlayManager::createScene()));
}
void LevelManager::update(float dt)
{
    if(LevelManager::m_isActive)
    {
        auto func = CallFuncN::create(CC_CALLBACK_0(LevelManager::GoToGamePlayScene,this));
        this->runAction(Sequence::create(DelayTime::create(2.0f), func,NULL));
        
        this->unscheduleUpdate();
    }
}